from functools import cached_property

from webutils.layers.managers import BinaryMixin
from webutils.layers.managers.redis import HashMixin, ListMixin

from ..handwriting import TransportFrame
from .base import BaseManager


class Handwriting(ListMixin, BinaryMixin, BaseManager):
    required_context = ['room_id', 'user_id']

    @cached_property
    def list_key(self):
        return self.get_redis_key('handwriting', self.room_id, self.user_id)

    def serialize(self, frame):
        assert isinstance(frame, TransportFrame)
        binary_s = frame.to_bytes()
        binary_s = frame.pack_timestamp(binary_s)
        return binary_s

    def deserialize(self, binary_s):
        return TransportFrame.from_bytes(binary_s, with_timestamp=True)


class HandwritingRefreshTime(HashMixin, BaseManager):
    required_context = ['room_id']

    @cached_property
    def hash_key(self):
        return self.get_redis_key('handwriting', 'refresh_at', self.room_id)
